import { defineStore } from "pinia";
import { Names } from "./store-names";
import { login, queryNotFriendsList, queryUserListByGroupId, queryUserListByUserId, register } from '../api/chat';
import type { TAllData, TFriendMessage, TFriendsListReq, TGroup, TGroupMessage, TLoginReq, TUserMap, TUserModel } from "./typings/chat";
import { useRequest, type RequestHookConfig } from "alova";
import { Socket, io } from "socket.io-client";
import { get, isEmpty } from "lodash";
import toast from "@/utils/toast";
import type { TRequestConfig } from "./typings/common";

const useChatStore = defineStore(Names.CHAT, {
  state() {
    return {
      user: <TUserModel>{},
      socketInstance: <{ server: Socket }>{},
      // 当前正在聊天的用户或群组
      currentFriend: <TGroup & TUserModel>{},
      // 聊天栏朋友列表
      friendGroupList: <TAllData>{
        friendData: [],
        userData: [],
        groupData: []
      },
      friendMessageList: <TFriendMessage[]>[],
      activeTab: 'chat',
      userListNoFriend: <TUserModel[]>[], // 查询到的用户列表（不包含好友），用于添加好友
      groupUserList: <TUserModel[]>[], //根据groupId查询用户数据(群成员)
      friendList: <TUserModel[]>[], // 朋友列表 by userId
      groupMessageList: <{
        groupMessages: TGroupMessage[],
        userData: Record<string, TUserModel>
      }>{},
      settingModelVisible: false, // 好友和群配置 抽屉 显示隐藏
    }
  },
  persist: {
    paths: ['user']
  },
  getters: {
    isChatting(): boolean {
      // 是否正在聊天中
      return !isEmpty(this.currentFriend)
    },
    isTabActive: (state) => (tab: string) => {
      return state.activeTab == tab
    },
    // 正在聊天的朋友或群组名称
    getChatName(state): string {
      return get(state.currentFriend, 'username') || get(state.currentFriend, 'groupName')
    },

  },
  actions: {
    login(lognReq: TLoginReq, fn: Function) {
      const { onSuccess } = useRequest(login(lognReq));
      onSuccess((res) => {
        if (res.data) {
          const data = res.data as { user: TUserModel, token: string }
          this.user = data.user

          localStorage.setItem('token', data.token)

          fn && fn(res.data);
        }
      });
    },
    loginout(fn: Function) {
      localStorage.removeItem('token')
      fn && fn()
    },
    register(registerReq: TLoginReq, fn: Function) {
      const { onSuccess } = useRequest(register(registerReq));
      onSuccess((res) => {
        if (res.data) {
          const data = res.data as { user: TUserModel, token: string }
          this.user = data.user

          localStorage.setItem('token', data.token)

          fn && fn(res.data);
        }
      });
    },
    queryNotFriendsList(friendsListReq: TFriendsListReq, fn: Function) {
      const { onSuccess } = useRequest(queryNotFriendsList(friendsListReq));
      onSuccess((res) => {
        if (res.data) {
          const data = res.data as TUserModel[]
          this.userListNoFriend = data

          fn && fn(res.data);
        }
      });
    },
    queryUserListByGroupId(groupId: string, config?: TRequestConfig, fn?: Function) {
      const { onSuccess } = useRequest(queryUserListByGroupId(groupId), { force: config?.force });
      onSuccess((res) => {
        if (res.data) {
          const data = res.data as TUserModel[]
          this.groupUserList = data
          fn && fn(res.data);
        }
      });
    },

    // 根据用户ID查询好友
    queryUserListByUserId(fn: Function) {
      const { onSuccess } = useRequest(queryUserListByUserId(this.user.userId));
      onSuccess((res) => {
        if (res.data) {
          const data = res.data as TUserModel[]
          this.friendList = data
          fn && fn(res.data);
        }
      });
    },
    //
    initSocket() {
      const socket = io('ws://127.0.0.1:8889', {
        transports: ["websocket"],
        query: {
          // chatStore.user.userId ||
          // userId: 'ae7c6cfb-a3cf-4160-8911-1868664b8eed',
          userId: this.user.userId
        }
      });
      this.socketInstance.server = socket
      this.handleChatData()
      this.listenMessage()
    },
    // 获取朋友列表数据
    handleChatData() {
      this.socketInstance.server.emit('chatData', {
        // userId: "ae7c6cfb-a3cf-4160-8911-1868664b8eed"
        userId: this.user.userId

      })
    },
    joinFriendSocket() {
      this.socketInstance.server.emit('joinFriendSocket', {
        userId: this.user.userId,
        friendId: this.currentFriend.userId
      })
    },
    joinGroupSocket() {
      this.socketInstance.server.emit('joinGroupSocket', {
        userId: this.user.userId,
        groupId: this.currentFriend.groupId
      })
    },

    // 向朋友发送私聊数据 friendMessage
    sendFrendMessage(content: string, messageType = 'text') {

      this.socketInstance.server?.emit('friendMessage', {
        // userId: "ae7c6cfb-a3cf-4160-8911-1868664b8eed",
        userId: this.user.userId,

        friendId: this.currentFriend.userId,
        content: content,
        messageType: messageType
      })
    },
    getFrendMessage() {
      this.socketInstance.server.emit('getFriendMessage', {
        // userId: "ae7c6cfb-a3cf-4160-8911-1868664b8eed",
        userId: this.user.userId,

        friendId: this.currentFriend.userId
      })
    },
    // 发送群组数据 groupMessage
    sendGroupMessage(content: string, messageType = 'text') {

      this.socketInstance.server?.emit('groupMessage', {
        // userId: "ae7c6cfb-a3cf-4160-8911-1868664b8eed",
        userId: this.user.userId,
        groupId: this.currentFriend.groupId,
        content: content,
        messageType: messageType
      })
    },
    getGroupMessage() {
      this.socketInstance.server.emit('getGroupMessage', {
       groupId: this.currentFriend.groupId,
       userId: this.user.userId
      })
    },

    // 添加好友
    addFriend(friendId: string) {
      this.socketInstance.server?.emit('addFriend', {
        // userId: "ae7c6cfb-a3cf-4160-8911-1868664b8eed",
        userId: this.user.userId,
        friendId: friendId,
      })
    },

    // 创建群并拉人进群
    addJoinGroup(friendIdList: string[], groupConfig: { groupName: string, avatar: string }) {
      this.socketInstance.server?.emit('add-join-group', {
        // userId: "ae7c6cfb-a3cf-4160-8911-1868664b8eed",
        userId: this.user.userId,
        friendIdList: friendIdList,
        groupConfig
      })
    },

     // 拉人进群
     usersJoinGroup(friendIdList: string[]) {
      this.socketInstance.server?.emit('usersJoinGroup', {
        // userId: "ae7c6cfb-a3cf-4160-8911-1868664b8eed",
        userId: this.user.userId,
        friendIdList: friendIdList,
        groupId: this.currentFriend.groupId
      })
    },

    // 退出群聊
    existGroup() {
      this.socketInstance.server?.emit('existGroup', {
        userId: this.user.userId,
        groupId: this.currentFriend.groupId
      })
    },
    // 删除好友
    existFriend() {
      this.socketInstance.server?.emit('existFriend', {
        userId: this.user.userId,
        friendId: this.currentFriend.userId
      })
    },

    listenMessage() {
      const socket = this.socketInstance.server

      socket.on('joinFriendSocket', (res) => {
        console.log('joinFriendSocket', res)
      })

      socket.on('joinGroupSocket', (res) => {
        console.log('joinGroupSocket', res)
      })

      socket.on('addGroup', (res) => {
        console.log('addGroupooo', res)
      })

      socket.on('joinGroup', (res) => {
        console.log('joinGroup', res)
      })
      // 发送消息，好友接受到的消息
      socket.on('friendMessage', (res) => {
        console.log('friendMessage', res, this.currentFriend)
        // 如果是当前正在聊天的朋友，添加最新消息到 this.friendMessageList
        // 朋友发送到消息 || 发送给朋友的消息
        if (this.currentFriend.userId === res.data.userId || this.currentFriend.userId === res.data.friendId) {
          this.friendMessageList.push(res.data)
        }
        //

      })

      socket.on('chatData', (res) => {
        console.log('user', res.data)
        this.friendGroupList = res.data
      })

      socket.on('groupMessage', (res) => {
        console.log('groupMessage', res)
        this.groupMessageList.groupMessages.push(res.data)
      })

      socket.on('getFriendMessage', (res) => {
        console.log('getFriendMessage', res)
        // 如果是刚刚添加的好友或者含有添加好友时系统消息（比如：添加好友成功）
        // 过滤掉系统发送给朋友的消息，不需要展示到自己的聊天记录中
        const filterData = res.data.filter((item: TFriendMessage) => {
          if (item.creator === 'SYSTEM') {
            return item.userId === this.user.userId
          }
          return true
        })
        this.friendMessageList = filterData
      })

      socket.on('getGroupMessage', (res) => {
        this.groupMessageList = res.data
        console.log('getGroupMessage', res)
      })

      socket.on('addFriend', (res) => {
        console.log('addFriend', res)
        // this.friendGroupList.friendData.push(res.data)
        toast?.add({ severity: 'success', summary: res.msg, life: 3000 });
      })

      socket.on('add-join-group', (res) => {
        console.log('add-join-group', res)
        // this.friendGroupList.friendData.push(res.data)
        toast?.add({ severity: 'success', summary: res.msg, life: 3000 });
      })

      socket.on('usersJoinGroup', (res) => {
        // 重新获取群消息
        this.getGroupMessage()
        this.queryUserListByGroupId(res.data.group.groupId, { force: true })
        toast?.add({ severity: 'success', summary: res.msg, life: 3000 });
      })

      // 退出群聊
      socket.on('existGroup', (res) => {
        // 重新好友列表
        this.handleChatData()
        console.log('existGroup', res)
        this.settingModelVisible = false
        this.groupMessageList.groupMessages.push(res.data)
        // toast?.add({ severity: 'success', summary: res.msg, life: 3000 });
      })

       // 删除好友
       socket.on('existFriend', (res) => {
        // 重新好友列表
        this.handleChatData()
        this.settingModelVisible = false
        console.log('existFriend', res)
        toast?.add({ severity: 'success', summary: res.msg, life: 3000 });
      })
    }

  }
})

export default useChatStore
